package com.control.back.halo.basic.utils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Optional;

import freemarker.template.DefaultObjectWrapper;
import freemarker.template.SimpleDate;
import freemarker.template.TemplateDateModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

@SuppressWarnings("deprecation")
public class FreemarkerObjectWrapper extends DefaultObjectWrapper {

    @Override
    public TemplateModel wrap(final Object obj) throws TemplateModelException {
        if (obj instanceof Optional) {
            Optional<?> p = (Optional<?>) obj;
            if (p.get() instanceof java.time.LocalDateTime) {
                LocalDateTime localDateTime = LocalDateTime.now();
                ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
                Date date = Date.from(zdt.toInstant());
                return new SimpleDate(date, TemplateDateModel.DATETIME);
            }
        }

        return super.wrap(obj);
    }
}
